package com.wgchao.authmanager.domain.model;

import com.wgchao.authmanager.domain.params.AgencyCreator;
import com.wgchao.authmanager.domain.params.AgencyUpdator;
import com.wgchao.authmanager.infrastructure.exception.ObjectDisabledException;
import lombok.*;

import java.util.Date;

/**
 * @作者：wgchao
 * @时间：20:14 2020/4/25 0025
 * @用途：机构
 **/
@Getter
@ToString
public class Agency extends DomainIdentify {

    private String agencyCode;

    private String agencyName;

    private String  remark;

    private boolean disabled;

    private Operator creator;

    private Operator lastupdator;



    protected Agency(String agencyCode, String agencyName, String remark, boolean disabled, Operator creator, Operator lastupdator) {
        this.agencyCode = agencyCode;
        this.agencyName = agencyName;
        this.remark = remark;
        this.disabled = disabled;
        this.creator = creator;
        this.lastupdator = lastupdator;
    }

    public Agency(Long id, Long version, String agencyCode, String agencyName, String remark,
                  boolean disabled, Operator creator, Operator lastupdator) {
        setId(id);
        this.agencyCode = agencyCode;
        this.agencyName = agencyName;
        this.remark = remark;
        this.disabled = disabled;
        this.creator = creator;
        setVersion(version);
    }

    /**
     *  新建机构
     * @param agencyCode
     * @param creator
     * @param operator
     * @return
     */
    public static Agency addNewAgency(String agencyCode, AgencyCreator creator, String operator){
        Agency agency = new Agency(agencyCode, creator.getAgencyName(), creator.getRemark(),false,
                new Operator(operator, new Date()), new Operator(operator, new Date()));
        return agency;
    }

    public boolean normal() {
        return !this.disabled;
    }

    /**
     *  修改机构信息
     * @param agencyUpdator
     * @param operator
     */
    public void reviseInfo(AgencyUpdator agencyUpdator, String operator){
        if(!normal()){
            throw new ObjectDisabledException("机构不可用");
        }
        if(agencyUpdator.getAgencyName() != null){
            this.agencyName = agencyUpdator.getAgencyName().orElse(null);
        }
        if(agencyUpdator.getRemark() != null){
            this.remark = agencyUpdator.getRemark().orElse(null);
        }
        this.lastupdator = new Operator(operator, new Date());
    }

    /**
     *  停用机构
     * @param operator
     */
    public void stopUsing(String operator) {
        this.disabled = true;
        this.lastupdator = new Operator(operator, new Date());
    }

    /**
     *  重新启用机构
     * @param operator
     */
    public void reEnable(String operator) {
        this.disabled = false;
        this.lastupdator = new Operator(operator, new Date());
    }
}
